import React, { FC, useEffect, useState } from 'react'
import { Form, Upload, Switch, Row, Col, Input, Select, Card, InputNumber } from 'antd'
import XlButtonFC from '@/components/xlbutton/xlbutton'
import type { UploadChangeParam } from 'antd/es/upload'
import { useAppDispatch, useAppSelector } from '@/store'
import { updateUserInfo } from '@/store/login'
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface'
import { Scrollbars } from 'react-custom-scrollbars'
import * as api from '@/api'
import { commonApi } from '@/utils/api'
import { IData, RootFilePath, FileTypes, ISettingInfo, IResponseCodeType } from '@/models/common'
import { UploadOutlinedIcon } from '@/models/icons'
import util from '@/utils/util'
import './adminsetting.scss'

export interface IViewModel {
  notAuth: boolean
}

const Index: FC = () => {
  const dispatch = useAppDispatch()
  const userInfo = useAppSelector((state) => state.login.userInfo)
  const [form] = Form.useForm()
  const [data, setData] = useState<IData<IViewModel>>({
    ViewModel: {
      notAuth: false
    }
  })
  useEffect(() => {
    
  }, [])

  const events = {
    onFinish(values: any) {
      console.log('Success:', values)
    },
    normFile(e: any) {
      if (Array.isArray(e)) {
        return e;
      }
      return e?.fileList;
    },
    onBeforeUpload(file: RcFile) {
      return false;
    },
    /**
   * 上传图片回调
   */
    onChangeUpload({ file, fileList, event }: UploadChangeParam, updateCode: string) {
      if (file.status === 'done') {
        let { code, data: uplodaData, message } = file.response
        if (code == IResponseCodeType.Success) {
          form.setFieldsValue({
            tenant_logo: [{
              uid: '-1',
              name: '',
              status: 'done',
              url: uplodaData.image_url,
              thumbUrl: uplodaData.image_url,
            }]
          })
          events.updateUserInfo(updateCode, uplodaData.image_url)
        } else {
          util.alertTip(message)
        }
      } else if (file.status === 'error') {
        util.alertTip("上传失败")
      } else if (file.status == 'uploading') {

      }
    },
    onTenantNameBlur() {
      let tenantname = form.getFieldValue('tenant_name')
      methods.requestUpdateTenantConfig('tenant_name', tenantname)
    },
    onSystemNameBlur() {
      let systemname = form.getFieldValue('system_name')
      methods.requestUpdateTenantConfig('system_name', systemname)
    },
    onOnlyOfficeEditorChange(checked: boolean) {
      let updateValue = checked ? '1' : '0'
      methods.requestUpdateTenantConfig('onlyoffice_editor', updateValue)
    },
    onPasswordStrengthVerifyChange(checked: boolean) {
      let updateValue = checked ? '1' : '0'
      methods.requestUpdateTenantConfig('password_strength_verify', updateValue)
    },
    onAutoExtractAttributeChange(checked: boolean) {
      let updateValue = checked ? '1' : '0'
      methods.requestUpdateTenantConfig('auto_extract_attribute', updateValue)
    },
    onPasswordExpiredTimeChange(value: string) {
      methods.requestUpdateTenantConfig('password_expired_time', value)
    },
    onInitialPasswordChange(value: string) {
      methods.requestUpdateTenantConfig('initial_password', value)
    },
    onFileChangeIntervalBlur() {
      let file_change_interval = form.getFieldValue('file_change_interval')
      methods.requestUpdateTenantConfig('file_change_interval', file_change_interval)
    },
    onFileChangeMaxSizeBlur() {
      let file_change_max_size = form.getFieldValue('file_change_max_size')
      methods.requestUpdateTenantConfig('file_change_max_size', file_change_max_size)
    },
    /**
     * 设置字段的值
     */
    setFieldsValue(settings: ISettingInfo[]) {
      if (settings && settings.length) {
        let systemNameInfo = settings.find(item => item.code == 'system_name')
        let tenantNameInfo = settings.find(item => item.code == 'tenant_name')
        let tenantLogoInfo = settings.find(item => item.code == 'tenant_logo')
        let onlyofficeEditorInfo = settings.find(item => item.code == 'onlyoffice_editor')
        let fileChangeIntervalInfo = settings.find(item => item.code == 'file_change_interval')
        let fileChangeMaxSizeInfo = settings.find(item => item.code == 'file_change_max_size')
        let passwordStrengthVerifyInfo = settings.find(item => item.code == 'password_strength_verify')
        let autoExtractAttributeInfo = settings.find(item => item.code == 'auto_extract_attribute')
        let passwordExpiredTimeInfo = settings.find(item => item.code == 'password_expired_time')
        let initialPasswordInfo = settings.find(item => item.code == 'initial_password')
        let system_name = ''
        let tenant_name = ''
        let tenant_logo: UploadFile[] = []
        let onlyoffice_editor = false
        let file_change_interval = '30'
        let file_change_max_size = '30'
        let password_strength_verify = false
        let auto_extract_attribute = false
        let password_expired_time = '30'
        let initial_password = '-1'
        if (systemNameInfo && systemNameInfo.value) {
          system_name = systemNameInfo.value
        }
        if (tenantNameInfo && tenantNameInfo.value) {
          tenant_name = tenantNameInfo.value
        }
        if (tenantLogoInfo && tenantLogoInfo.value) {
          tenant_logo = [{
            uid: '-1',
            name: '',
            status: 'done',
            url: tenantLogoInfo.value,
            thumbUrl: tenantLogoInfo.value,
          }]
        }
        if (onlyofficeEditorInfo && onlyofficeEditorInfo.value) {
          onlyoffice_editor = onlyofficeEditorInfo.value == '1'
        }
        if (fileChangeIntervalInfo && fileChangeIntervalInfo.value) {
          file_change_interval = fileChangeIntervalInfo.value
        }
        if (fileChangeMaxSizeInfo && fileChangeMaxSizeInfo.value) {
          file_change_max_size = fileChangeMaxSizeInfo.value
        }
        if (passwordStrengthVerifyInfo && passwordStrengthVerifyInfo.value) {
          password_strength_verify = passwordStrengthVerifyInfo.value == '1'
        }
        if (autoExtractAttributeInfo && autoExtractAttributeInfo.value) {
          auto_extract_attribute = autoExtractAttributeInfo.value == '1'
        }
        if (passwordExpiredTimeInfo && passwordExpiredTimeInfo.value) {
          password_expired_time = passwordExpiredTimeInfo.value
        }
        if (initialPasswordInfo && initialPasswordInfo.value) {
          initial_password = initialPasswordInfo.value
        }
        form.setFieldsValue({
          system_name,
          tenant_name,
          tenant_logo,
          onlyoffice_editor,
          file_change_interval,
          file_change_max_size,
          password_strength_verify,
          auto_extract_attribute,
          password_expired_time,
          initial_password
        })
      }
    },
    updateUserInfo(updateCode: string, updateValue: string) {
      let newUserInfo = {
        ...userInfo,
        [updateCode]: updateValue
      }
      localStorage.setItem("userinfo", JSON.stringify(newUserInfo))
      dispatch(updateUserInfo(newUserInfo))
    },
  }
  const methods = {
    async requestTenantConfig() {
      let res = await api.common.getTenantConfig<ISettingInfo[]>(null)
      let { code, message } = res
      if (code == IResponseCodeType.Success) {
        events.setFieldsValue(res.data)
      } else if (code == IResponseCodeType.NotAuth) {
        const { ViewModel } = data
        ViewModel.notAuth = true
        setData({ ...data })
      } else {
        util.alertTip(message)
      }
    },
    async requestUpdateTenantConfig(updateCode: string, updateValue?: string) {
      if (updateValue == null || updateValue == undefined) {
        return
      }
      let res = await api.common.updateSettingString({
        code: updateCode,
        value: updateValue
      })
      let { code, message } = res
      if (code == IResponseCodeType.Success) {
        if (updateCode == 'system_name' || updateCode == 'tenant_name') {
          events.updateUserInfo(updateCode, updateValue)
        }
      } else {
        util.alertTip(message)
      }
    },
    resetFormItem() {
      form.resetFields()
    },
    renderPage() {
      if (data.ViewModel.notAuth) {
        return null
      }
      return <Card title="系统参数设置">
        <Form
          form={form}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 8 }}
          onFinish={events.onFinish}
          autoComplete="off"
          labelWrap
          className='setting-form-wrapper'
          initialValues={{
            password_expired_time: "30",
            initial_password: "-1"
          }}
        >
          <Scrollbars autoHide>
            <Form.Item
              key='system_name'
              label='系统名称'
              name='system_name'
              rules={[{ required: true }]}
            >
              <Input placeholder='请输入系统名称' onBlur={events.onSystemNameBlur} />
            </Form.Item>
            <Form.Item
              key='tenant_name'
              label='公司名称'
              name='tenant_name'
              rules={[{ required: true }]}
            >
              <Input placeholder='请输入公司名称' onBlur={events.onTenantNameBlur} />
            </Form.Item>
            <Form.Item
              key='tenant_logo'
              label='公司图标'
              name='tenant_logo'
              rules={[{ required: true }]}
              valuePropName="fileList"
              getValueFromEvent={events.normFile}
              extra="推荐尺寸：35*40"
            >
              <Upload
                action={commonApi.updatesettingimage_url}
                data={{
                  code: "tenant_logo",
                  token: util.getToken()
                }}
                onChange={(e) => { events.onChangeUpload(e, 'tenant_logo') }}
                name='file'
                listType="picture"
                showUploadList={{
                  showRemoveIcon: false,
                  showPreviewIcon: false
                }}
                maxCount={1}
                accept='image/*'
                progress={
                  {
                    strokeColor: {
                      '0%': '#108ee9',
                      '100%': '#87d068',
                    },
                    strokeWidth: 3,
                    format: percent => percent && `${parseFloat(percent.toFixed(2))}%`,
                  }
                }
              >
                <XlButtonFC type='primary' icon={<UploadOutlinedIcon />}>点击上传</XlButtonFC>
              </Upload>
            </Form.Item>
            <Form.Item
              key='onlyoffice_editor'
              label='启用在线Office编辑器'
              name='onlyoffice_editor'
              valuePropName="checked"
            >
              <Switch onChange={events.onOnlyOfficeEditorChange} />
            </Form.Item>
            <Form.Item
              key='password_strength_verify'
              label='开启密码强度校验'
              name='password_strength_verify'
              valuePropName="checked"
            >
              <Switch onChange={events.onPasswordStrengthVerifyChange} />
            </Form.Item>
            <Form.Item
              key='auto_extract_attribute'
              label='开启自动提取属性值'
              name='auto_extract_attribute'
              valuePropName="checked"
            >
              <Switch onChange={events.onAutoExtractAttributeChange} />
            </Form.Item>
            <Form.Item
              key='password_expired_time'
              label='密码过期时间'
              name='password_expired_time'
            >
              <Select
                onChange={events.onPasswordExpiredTimeChange}
                placeholder='请选择'
                options={[
                  {
                    value: '0',
                    label: '永不过期',
                  },
                  {
                    value: '30',
                    label: '30天',
                  },
                  {
                    value: '90',
                    label: '90天',
                  },
                  {
                    value: '180',
                    label: '180天',
                  },
                ]}
              />
            </Form.Item>
            <Form.Item
              key='initial_password'
              label='初始密码'
              name='initial_password'
            >
              <Select
                onChange={events.onInitialPasswordChange}
                placeholder='请选择'
                options={[
                  {
                    value: '123456',
                    label: '默认值（123456）',
                  },
                  {
                    value: '-1',
                    label: '随机',
                  },
                ]}
              />
            </Form.Item>
            <Form.Item
              key='file_change_interval'
              label='文件变更最小间隔时间（秒）'
              name='file_change_interval'
              rules={[{ required: true }]}
            >
              <InputNumber placeholder='请输入文件变更最小间隔时间，不能低于5s' min={5} style={{ width: "100%" }} onBlur={events.onFileChangeIntervalBlur} />
            </Form.Item>
            <Form.Item
              key='file_change_max_size'
              label='文件变更最大文件大小（M）'
              name='file_change_max_size'
              rules={[{ required: true }]}
            >
              <InputNumber placeholder='文件变更支持的最大文件，不能超过30M' min={1} max={30} style={{ width: "100%" }} onBlur={events.onFileChangeMaxSizeBlur} />
            </Form.Item>
          </Scrollbars>
        </Form>
      </Card>
    }
  }
  return methods.renderPage()
}
export default Index
